﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using CSparse.Storage;
using TestApp.Test;

namespace TestApp
{
    public partial class FormSpy : Form
    {
        Bitmap bitmap;

        public FormSpy()
        {
            InitializeComponent();
        }

        private void FormSpy_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                this.Hide();
                e.Cancel = true;
            }
        }

        public void Spy<T>(CompressedColumnStorage<T> matrix)
            where T : struct, IEquatable<T>, IFormattable
        {
            if (matrix == null)
            {
                return;
            }

            Size size = this.ClientSize;

            if (bitmap == null)
            {
                bitmap = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppPArgb);
            }

            Graphics g = Graphics.FromImage(bitmap);

            g.Clear(Color.White);

            Color color = Color.FromArgb(100, 0, 0, 0);

            int i;

            int m = matrix.RowCount;
            int n = matrix.ColumnCount;
            int nz = matrix.NonZerosCount;

            int[] ai = matrix.RowIndices;
            int[] ap = matrix.ColumnPointers;

            int max = Math.Max(m, n);

            if (max >= size.Width * 0.9)
            {
                g.Dispose();

                for (int j = 0; j < n; j++) // Column j
                {
                    for (int p = ap[j]; p < ap[j + 1]; p++)
                    {
                        i = ai[p]; // A(i,j) is nonzero
                        bitmap.SetPixel((i * size.Width) / m, (j * size.Height) / n, Color.Black);
                    }
                }
            }
            else
            {
                int left, right, pixel = Math.Max(size.Width / max, 1);

                for (int j = 0; j < n; j++) // Column j
                {
                    for (int p = ap[j]; p < ap[j + 1]; p++)
                    {
                        i = ai[p]; // A(i,j) is nonzero

                        left = (i * size.Width) / m;
                        right = (j * size.Height) / n;
                        i = ai[p]; // A(i,j) is nonzero
                        g.FillRectangle(Brushes.Black, left, right, pixel, pixel);
                    }
                }

                g.Dispose();
            }

            this.Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            if (bitmap != null)
            {
                e.Graphics.DrawImageUnscaled(bitmap, 0, 0);
            }
        }
    }
}
